package com.yyge.mapper.impl;

import com.yyge.entity.AddrInfo;
import com.yyge.mapper.AddrInfoMapper;
import com.yyge.util.DruidDataSourceHandler;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.sql.SQLException;

public class AddrInfoMapperImpl implements AddrInfoMapper {
    @Override
    public int insert(AddrInfo addrInfo) {
        // 得到连接池
        DataSource dataSource = DruidDataSourceHandler.getDataSource();
         // 基于QueryRunner类的对象来进行
        QueryRunner queryRunner=new QueryRunner(dataSource);
        String sql="insert into addr_info"+
                " (addr_id, addr_pre_id, addr_info, lev, value_1)"+
                "values (?,?,?,?,?)";
        Object[] params={
                addrInfo.getAddr_id(),
                addrInfo.getAddr_pre_id(),
                addrInfo.getAddr_info(),
                addrInfo.getLev(),
                addrInfo.getValue_1()
        };

        try {
           return queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteByPrimaryKey(Integer key) {
        String sql="delete from addr_info where addr_id=?";
        DataSource dataSource=DruidDataSourceHandler.getDataSource();
        QueryRunner queryRunner=new QueryRunner(dataSource);
        try {
            return queryRunner.update(sql,key);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateByPrimaryKey(AddrInfo addrInfo) {
        String sql="update addr_info set "+
           "addr_pre_id=?,"+
           "addr_info=?,"+
           "lev=?,"+
           "value_1=?"+
           "where addr_id=?";
        DataSource dataSource=DruidDataSourceHandler.getDataSource();
        QueryRunner queryRunner=new QueryRunner(dataSource);
        Object[] params= {
            addrInfo.getAddr_pre_id(),
            addrInfo.getAddr_info(),
            addrInfo.getLev(),
            addrInfo.getValue_1(),
            addrInfo.getAddr_id()
        };
        try {
           return queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public AddrInfo selectByPrimaryKey(Integer key) {
        String sql="select * from addr_info where addr_id=?";
        QueryRunner queryRunner=new QueryRunner(DruidDataSourceHandler.getDataSource());
        ResultSetHandler<AddrInfo> rsh= new BeanHandler<>(AddrInfo.class);
        try {
            AddrInfo addrInfo=queryRunner.query(sql,rsh,key);
            return addrInfo;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
